package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;
    @Override
    public PageResponse<RoleVo> selectPage(Integer pageNum, Integer pageSize, RoleDto roleDto) {
        //分页数据
        PageHelper.startPage(pageNum, pageSize);
        //数据查询
        Page<Role> roles=roleMapper.selectPage(roleDto);
        return PageResponse.of(roles,RoleVo.class);

    }

    @Override
    public void addRole(RoleDto roleDto) {
        //Dto转为实体类接收参数
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public List<String> findCheckedResources(Long roleId) {
        List<String> resources =roleResourceMapper.findCheckedResources(roleId);
        return resources;
    }

    @Transactional
    @Override
    public void deleteRole(String roleIds) {
        roleMapper.deleteByRoleId(roleIds);
        roleResourceMapper.deleteByRoleId(roleIds);
    }

    @Override
    public Boolean updateRole(RoleDto roleDto) {
        //将传入的Dto转换为实体类
        Role role=BeanUtil.toBean(roleDto,Role.class);
        //先更改角色表
        roleMapper.updateByPrimaryKeySelective(role);
        //判断角色是否含有中间表权限数据//判断是否为空
        if(ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())){
            return true;
            //如果没有返回true方法结束
        }
        //修改角色对应数据
        roleResourceMapper.deleteByPrimaryKey(role.getId());
        //批量插入角色全部数据
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        List<RoleResource> resources = Arrays.stream(checkedResourceNos)
                .map(s -> {
            RoleResource roleResource = new RoleResource();
            roleResource.setRoleId(role.id);
            roleResource.setResourceNo(s);
            roleResource.setDataState(SuperConstant.DATA_STATE_0);
            return roleResource;
        }).collect(Collectors.toList());
        roleResourceMapper.batchInsert(resources);
        return true;
    }

    @Override
    public List<RoleVo> getAllRoles() {
        List<Role> roles = roleMapper.getAllRoles();
        return BeanUtil.copyToList(roles, RoleVo.class);
    }
}
